#!/bin/bash

#Script used to initiate global environment based on file and some post action
if [[ -z "${SYSTEM_SHELL_CONFIG_HOME}" ]]; then
    export SYSTEM_SHELL_CONFIG_HOME="$HOME/.shell" 
fi

export SYSTEM_GLOBAL_CONFIG_FILE="${SYSTEM_SHELL_CONFIG_HOME}/local_data"

ifs_s=$IFS

IFS=': '
bash_envs=( $(head -n 1 ${SYSTEM_GLOBAL_CONFIG_FILE}) )
describe=$(tail  -n 1 ${SYSTEM_GLOBAL_CONFIG_FILE})

#echo $SHELL

__write_joined_array(){

    result=""

    for word in ${bash_envs[@]}; do 
        result+=$word" "
    done 

    echo $result
    echo $result > ${SYSTEM_GLOBAL_CONFIG_FILE}
    echo $describe >> ${SYSTEM_GLOBAL_CONFIG_FILE}
}



__update_local_git_repos(){

    declare -a repos
    repos=(
        ~/gitworkspace/.dotfiles/
        ~/gitworkspace/.notes/
        ~/gitworkspace/.blog/
        ~/gitworkspace/.doc/
    )
    
    for repo in ${repos[@]} ; do
    
        cd $repo
        git fetch origin; git pull origin master;
    done;
    
    cd ~
}



__check_system_started_or_prepare(){

    index=1

    if [[ ${#bash_envs} -eq 6 ]]; then
        index=2
    fi

    if [[ ${#bash_envs} -eq 7 ]]; then
        index=1
    fi

    #it's not the first time to run this file
    if [[ ${bash_envs[$index]} == "true" ]]; then
        started="true"
        export started
        return 
    
    #the first time to run this file
    else
        echo ${#bash_envs}
        echo ${bash_envs[@]}
        bash_envs[$index]="true"
        started="true"
        export started
        echo "not started yet!"
        
        #update the started status and write into file
        __write_joined_array
    
        __update_local_git_repos
        
        echo "Finish System Startup Configuration"
    fi
}



#check if shell already logined before 
__check_system_started_or_prepare

IFS=$ifs_s
